﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Sitecore.Data.Items;
using Sitecore.Data;
using SitecoreTranslation.Integration.Settings;
using Sitecore.Globalization;
using Sitecore.Publishing;
using Sitecore.Data.Fields;

namespace SitecoreTranslation.Integration
{
	public class ImportAction : BaseAction
	{
		public ImportAction(String ExportFileName, String DataBaseName, String ItemPath) : base(ExportFileName, DataBaseName, ItemPath)
		{
		}
		public void Execute()
		{
			using (new Sitecore.SecurityModel.SecurityDisabler())
			{

				XmlDocument document = new XmlDocument();
				

				document.Load(_fileName);
				XmlElement itemRoot = (XmlElement)document.GetElementsByTagName(ItemName)[0];

				string sitemId = itemRoot.GetAttribute(ItemId);

				ID  itemId = new ID(sitemId);
				Item item = Database.Items[itemId];

				TranslationSettings settings = new TranslationSettings();

				settings.Deserialize(document);


				TemplateItem template = item.Template;

				Item translatedItem = item.Parent.Add(item.Name, template);

				Language targetLanguage = null;

				foreach(Language lang in translatedItem.Languages)
				{
					if(string.Compare(lang.Name, settings.TargetLanguage, true) == 0)
					{
						targetLanguage = lang;

						break;
					}
				}

				if(targetLanguage == null)
				{
					throw new ArgumentException(string.Format("Language '{0}' is not found for item '{1}' and can't be specified!", settings.TargetLanguage, item.Name));
				}

				ApplyTranslation(translatedItem, document);

				PublishOptions options = new PublishOptions(Database, Database, PublishMode.SingleItem, targetLanguage, DateTime.Now);

				//Activate the publishpipeline
				Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(item.ID, options);

			}
		}

		private void ApplyTranslation(Item translatedItem, XmlDocument document)
		{
			//Begin editing
			translatedItem.Editing.BeginEdit();

			try
			{
				XmlNodeList nodes = document.SelectNodes(string.Format("/{0}/{1}/{2}", RootName, ItemName, FieldName));

				foreach (XmlNode node in nodes)
				{
					if (node is XmlElement)
					{
						XmlElement element = node as XmlElement;
						string fileId = element.GetAttribute(FileId);

						ID id = new ID(fileId);

						Field f = translatedItem.Fields[id];

						f.Value = node.InnerXml;
					}
				}
			}
			finally
			{
				//Close the editing state
				translatedItem.Editing.EndEdit();
			}

		}
	}
}
